//
//  MeMoreListViewController.m
//  NBProduct
//
//  Created by hl on 15/11/16.
//  Copyright (c) 2015年 ping. All rights reserved.
//

#import "MeMoreListViewController.h"
#import "MeGuanYuViewController.h"
#import "SuggestViewController.h"
#import "LibWebViewViewController.h"
#import "ME_moreVCShareView.h"
//#import "MeZhangHuViewController.h"
//#import "SheQuErweiMaViewController.h"
#import "MeZhangHaoTableViewCell.h"

@interface MeMoreListViewController ()<UITableViewDataSource,UITableViewDelegate,ME_moreVCShareViewDelegate,UIAlertViewDelegate>{//TencentSessionDelegate
    UITableView *table;
    NSArray     *titleArr;
    ME_moreVCShareView *_shareView;
    
    UIButton           *tapBtn;
    NSString           *_url;
    UIAlertView        *_shareAlertView;
}

@end

@implementation MeMoreListViewController
-(void)viewWillAppear:(BOOL)animated{
//    self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:2];
    [self drawNavWithTitle:@"设置" WithColor:[UIColor whiteColor]];
    [self drawBackButton];
    [self drawView];
    // Do any additional setup after loading the view.
}
-(void)drawView{
    
    titleArr = @[@[@"关于未涞商城",@"用户协议"],@[@"支付帮助",@"清空缓存"],@[@"意见反馈",@"应用分享"]];
    
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + 20, KScreenWidth, 36* _kscH *7 + 20 *2) style:UITableViewStyleGrouped];
    table.delegate = self;
    table.dataSource = self;
    table.scrollEnabled = NO;
    [self.view addSubview:table];

    UIButton *outBtn = [[UIButton alloc] initWithFrame:CGRectMake(13*_kscW , table.bottom + 30, KScreenWidth - 26*_kscW, 35*_kscH)];
 
//    [outBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    outBtn.titleLabel.font = [UIFont fontWithName:Text_Name size:15.0];
    [outBtn addTarget:self action:@selector(outLogin) forControlEvents:UIControlEventTouchUpInside];
//    [outBtn setImage:[UIImage imageNamed:@"me_退出登录按钮"] forState:UIControlStateNormal];
    outBtn.layer.cornerRadius = 5;
    [outBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    outBtn.font = [UIFont fontWithName:Text_Name size:13];
    [outBtn setTitleColor:MaintextColor forState:UIControlStateNormal];
    outBtn.backgroundColor = ZONGCOLOR;
    [self.view addSubview:outBtn];
    
    tapBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, KScreenHeight, KScreenWidth, KScreenHeight - 64)];
    tapBtn.backgroundColor = [UIColor blackColor];
    tapBtn.alpha = 0.7;
    [tapBtn addTarget:self action:@selector(showORhiddenView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tapBtn];
    
    _shareView = [[ME_moreVCShareView alloc] initWithFrame:CGRectMake(0, KScreenHeight, KScreenWidth, 70*_kscH)];
    _shareView.delegate =self;
    _shareView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_shareView];
}
-(void)outLogin{
    [self defaultSaveUserName:@""];
//    [self defaultSavePortrait:@""];
//    [self defaultSaveXiaoQuId:@""];
//    [self defaultSaveXiaoQuName:@""];
//    [self defaultSavePassWord:@""];
//    [self defaultSaveLonginType:@""];
//    [self defaultSaveOpenID:@""];
//    [self defaultSaveHuiYuan:@""];
//    [self defaultSaveXiaoQuId:@""];
//    [self defaultSaveXiaoQuName:@""];
//    [self defaultSaveYeZhuFangHao:@""];
//    [self defaultSaveLouHao:@""];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserInfo" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"用户名" object:@"1"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return titleArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *arr = [titleArr objectAtIndex:section];
    return arr.count;
}
//意见反馈  关于西灰内 清空缓存 用户协议  支付帮助
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MeZhangHaoTableViewCell*cell = [[MeZhangHaoTableViewCell alloc] init];
    
    [cell.detailLab setHidden:YES];
    [cell.lineLab setHidden:YES];
    cell.signLab.text = [[titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForFootInSection:(NSInteger)section{
//    return 0.1;
//}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 36*_kscH;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MeGuanYuViewController *guanyu = [[MeGuanYuViewController alloc] init];
            [self.navigationController pushViewController:guanyu animated:YES];
        }else if (indexPath.row == 1){
            LibWebViewViewController *lib = [[LibWebViewViewController alloc] init];
            lib.code = @"YHXY";
            lib.myTitle = @"用户协议";
            [self.navigationController pushViewController:lib animated:YES];
        }
    }else if(indexPath.section == 1){
        if (indexPath.row == 1) {
            
            float huanCun = [self fileSizeAtPath:nil];
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%fM",huanCun] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清理", nil];
            alertView.tag = 1;
            [alertView show];
        }else if(indexPath.row == 0){
            LibWebViewViewController *lib = [[LibWebViewViewController alloc] init];
            lib.code = @"ZFBZ";
            lib.myTitle = @"支付帮助";
            [self.navigationController pushViewController:lib animated:YES];
        }
    }else if (indexPath.section == 2){
        
        if (indexPath.row == 0) {
            SuggestViewController *fanKui = [[SuggestViewController alloc] init];
            [self.navigationController pushViewController:fanKui animated:YES];
        }else{
            [UIView animateWithDuration:0.5 animations:^{
                tapBtn.frame = CGRectMake(0, 64, KScreenWidth, KScreenHeight - 64);
                _shareView.frame = CGRectMake(0, KScreenHeight-70*_kscH, KScreenWidth, 70*_kscH);
            }];

        }
        
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            
            [[EMSDImageCache sharedImageCache] clearDisk];
            
            [[EMSDImageCache sharedImageCache] clearMemory];
            [self myClearCacheAction];
        }
    }else{
        if (buttonIndex == 0) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:_url]];
        }
    }
    
}

-(float)fileSizeAtPath:(NSString *)path{
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    
    NSLog(@"files :%lu",(unsigned long)[files count]);
    NSFileManager *fileManager=[NSFileManager defaultManager];
    long long size = 0;
    
    for (NSString *p in files) {
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        
          size  = [fileManager attributesOfItemAtPath:path error:nil].fileSize + size;
         }
     }
    
//    
//    NSFileManager *fileManager=[NSFileManager defaultManager];
//    if([fileManager fileExistsAtPath:path]){
//        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
//        return size/1024.0/1024.0;
//    }
    return size/1024.0/1024.0;
}

-(void)myClearCacheAction{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
        
        NSLog(@"files :%lu",(unsigned long)[files count]);
        
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}

-(void)clearCacheSuccess

{
    [TCUtils showAlertViewWithTitle:@"提示" message:@"清理成功" delegate:nil cancel:@"确定" other:nil tag:0];
//    NSLog(@"清理成功");
    

}
#pragma mark 分享
-(void)showORhiddenView:(UIButton *)btn{
    [UIView animateWithDuration:0.5 animations:^{
        tapBtn.frame = CGRectMake(0, KScreenHeight, KScreenWidth, KScreenHeight - 64);
        _shareView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, 70*_kscH);
    }];
}

-(void)shareButtonClicked:(UIButton *)btn{
    if (btn.tag == 0 || btn.tag == 1) {
        if ([WXApi isWXAppInstalled]) {//是否安装微信
            if ([WXApi isWXAppSupportApi]) {//是否支持打开微信
                
                
                WXWebpageObject *webObj = [WXWebpageObject object];
                webObj.webpageUrl = @"";
                
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = @"未涞商城APP";
                message.description = @"快来加入未涞商城吧";
                message.mediaObject = webObj;
                
                
                UIImage *desImage = [UIImage imageNamed:@"XHN_TB"];
                
//                UIImage *thumbImg = [self thumbImageWithImage:desImage limitSize:CGSizeMake(150, 150)];
//                message.thumbData = UIImageJPEGRepresentation(thumbImg, YaSuoBi);
                // NSLog(@"%@,%d",desImage,message.thumbData.length);
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                if (btn.tag == 0) {
                    //好友
                    req.scene = WXSceneSession;
                }else{
                    //朋友圈
                    req.scene = WXSceneTimeline;
                }
                
                req.bText = NO;
                req.message = message;
                [WXApi sendReq:req];
                
                
            }
            
        }else{
            //没有安装微信,返回微信安装的地址
            _url = [WXApi getWXAppInstallUrl];
            [self showShareAlertViewWithMessage:@"检测到您手机没有安装微信,是否前往下载"];
         }
     }else{
//        if ([QQApiInterface isQQInstalled]) {
//            if ([QQApiInterface isQQSupportApi]) {
//                //注册qq
//                TencentOAuth * _tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQOpenID andDelegate:self]; //注册
//                
//                
//                NSString *utf8String = APPDOWNLOADHTML;
//                NSString *title = @"庭树生活APP下载";
//                NSString *description = @"庭树生活APP,快来加入吧!";
//                UIImage *previewImage = [UIImage imageNamed:@"AppIcon"];
//                
//                
//                QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String] title:title description:description previewImageData:UIImageJPEGRepresentation(previewImage, YaSuoBi)];
//                //这个貌似是直接拉起QQ空间分享的值，0为NO，1为YES，但是也补起作用了。
//                uint64_t cflag = 0;
//                [newsObj setCflag:cflag];
//                QQApiObject* objc = newsObj;
//                SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:objc];
//                
//                
//                //将内容分享到qq
//                QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        
//            }else{
//                //不支持打开
//                [TCUtils showAlertViewWithTitle:nil message:@"您的设备不允许打开qq" delegate:nil cancel:@"确定" other:nil tag:9];
//            }
//        }else{
//            //未安装qq
//            _url = [QQApiInterface getQQInstallUrl];
//            
//            [self showShareAlertViewWithMessage:@"您尚未安装qq,是否要安装"];
//        }
    }
    
}
-(void)showShareAlertViewWithMessage:(NSString *)message{
    if (_shareAlertView) {
        _shareAlertView.message = message;
        
    }else{
        _shareAlertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"去下载" otherButtonTitles:@"不了", nil];
        _shareAlertView.tag = 0;
    }
    [_shareAlertView show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
